package com.xuecheng.content.controller;

import com.xuecheng.api.content.FileManegerApi;
import com.xuecheng.api.content.model.upload.UploadTokenResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p></p>
 *
 * @Description:
 */
@Slf4j
@RestController
public class FileManagerController implements FileManegerApi {


    @Autowired
    private RestTemplate restTemplate;

    /*
    * file.service.url=http://127.0.0.1:56082/farming/generatetoken?origin=qiniu
        #文件存储空间名称
        file.service.bucket= xc134-static-imgs


        #前端上传图片时需要的数据
        #文件存储区域的地址
        file.service.upload.region = http://upload.qiniu.com
        #文件访问的cdn加速域名
        cdn.domain = r2fsp0zfc.hd-bkt.clouddn.com


        file.token.type = 1
        file.token.deadline = 3600
    *
    * */
    @Value("${file.service.url}")
    private String url;
    @Value("${file.service.bucket}")
    private String bucket;
    @Value("${file.service.upload.region}")
    private String region;
    @Value("${cdn.domain}")
    private String domain;
    @Value("${file.token.type}")
    private String tokenType;
    @Value("${file.token.deadline}")
    private int deadline;

    @GetMapping("common/qnUploadToken")
    public UploadTokenResult getUploadToken() {


        // 1.发送请求到文件微服务中获得上传图片的凭证


        HashMap<String, Object> headerData = new HashMap<>();

        headerData.put("tokenType", tokenType);
        headerData.put("scope", bucket);
        headerData.put("deadline", deadline);

        // 生成七牛云文件的 key 值
        String fileKey = UUID.randomUUID().toString() + RandomStringUtils.randomAlphanumeric(16);


        headerData.put("key", fileKey);


        UploadTokenResult tokenResult = null;
        try {
            ResponseEntity<Map> responseEntity = restTemplate.postForEntity(url, headerData, Map.class);


            // 2.封装结果数据给前端

            /*
            * 文件服务的获得上传图片凭证的接口返回结果
            *
            * */


            tokenResult = null;

            HttpStatus statusCode = responseEntity.getStatusCode();
            Map body = responseEntity.getBody();

            if (HttpStatus.OK == statusCode) {


                tokenResult = new UploadTokenResult();

                tokenResult.setQnToken(body.get("result").toString());
                tokenResult.setTokenType(tokenType);
                tokenResult.setDeadline(deadline);
                tokenResult.setDomain(domain);
                tokenResult.setKey(fileKey);
                tokenResult.setScope(bucket);
                tokenResult.setUp_region(region);
            } else {

                log.error("获得上传图片令牌失败：{}",body.get("msg"));

                tokenResult = new UploadTokenResult();
            }
        } catch (RestClientException e) {

            log.error("请求文件微服务失败：{}",e.getMessage());

            tokenResult = new UploadTokenResult();

        }


        return tokenResult;
    }
}
